'use strict';

var co = require('co'),
  debug = require('debug'),
  log = debug('yozh:config:log'),
  error = debug('yozh:config:error'),
  verbose = debug('yozh:config:verbose'),
  _ = require('underscore')._,
  config = require('./config'),
  run = require('../lib/run')(),
  rules = require('./rules');

module.exports = exports = function myRobFunc(opts) {
  var myRob = {};
  myRob.init = function(robrule) {
    // this.add(robrule);

    opts.webot.set('hello', {
      description: 'hello',
      pattern: /(hi|hello|你好)[\.\。\!\！]*/i,
      handler: co.wrap(function *(info){
        return new Function('rules', 'return rules.sayHi("你好");')(rules);
      })
    });

    opts.webot.set('subscribe me', {
      description: '关注通知',
      pattern: function(info) {
        return info.is('event') && info.param.event === 'subscribe';
      },
      handler: co.wrap(function *(info){
        return '感谢你的关注，发送help|more获取更多消息';
      })
    });

    opts.webot.set('unsubscribe me', {
      description: '取消关注通知',
      pattern: function(info) {
        return info.is('event') && info.param.event === 'unsubscribe';
      },
      handler: co.wrap(function *(info){
        return '取消关注的事件';
      })
    });

    opts.webot.set('more', {
      description: '发送help|more获取更多帮助',
      pattern: /(help|more|\?|\？)[\?\？]*/i,
      handler: co.wrap(function *(info){
        var reply = '';
        _.map(opts.webot.gets(), function(rule, key) {
          // log(rule, key);
          var txts = rule.name.split('##');
          if (txts.length > 1) {
            if (txts[1] === info.uid) {
              reply = reply + '>' + txts[0] + '指令(个人):\n    ' +
                rule.description + '\n';
            }
          } else {
            reply = reply + '>' + rule.name + '指令:\n    ' +
              rule.description + '\n';
          }
        });
        verbose('rules: ', reply);
        return '当前的指令：\n' + reply;
      })
    });

    //所有消息都无法匹配时的fallback
    opts.webot.set('other', {
      description: '所有消息都无法匹配时',
      pattern: /.*/,
      handler: co.wrap(function *(info){
        // 利用 error log 收集听不懂的消息，以利于接下来完善规则
        // 你也可以将这些 message 存入数据库
        log('unhandled message: %s', info.text);
        info.flag = true;
        var txts = info.text.split('##');
        var txt = '';
        if (txts.length > 1) {
          txt = txts[0];
        } else {
          txt = info.text;
        }
        return '你发送了[' + txt +
          '],可惜我太笨了,听不懂. 发送: help 查看可用的指令';
      })
    });
  };

  myRob.add = function(robrule) {
    _.map(robrule, function(rule, key) {
      // opts.webot.set({
      //   name: rule.name,
      //   description: rule.description,
      //   pattern: rule.pattern,
      //   handler: rule.handler
      // });
      var openId = rule.openId || '';
      var nameStr, patternStr;
      if (openId !== '') {
        nameStr = rule.name + config.rulePrefix + openId;
        // patternStr = rule.pattern + '(' + config.rulePrefix + openId + ')$';
      } else {
        nameStr = rule.name;
        // patternStr = rule.pattern;
      }
      opts.webot.set(nameStr, {
        name: nameStr,
        description: rule.description,
        pattern: rule.pattern,
        handler: co.wrap(function *(info){
          yield new Function('rules', 'try{' +
            rule.handler + '}catch(e){return false;}')(rules);
          // return rules.sayHello('123');
        })
      });
    });
  };

  myRob.find = function(name) {
    return opts.webot.get(name);
  };

  myRob.update = function(name, rule) {
    return opts.webot.update(name, rule);
  };

  myRob.delete = function(name) {
    return opts.webot.remove(name);
  };

  var callBackHandler = function(info, next) {
    return new Function(info.handler)();
  };

  return myRob;
};


